package org.mspring.mlog.freemarker.directive;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.mspring.mlog.cache.ArticleCacheService;
import org.mspring.mlog.entity.ArticleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 热门文章
 *
 * @author Gao Youbo
 * @since 2015-01-24 08:40
 */
@Component
public class LatestArticleDirectiveModel implements TemplateDirectiveModel {

    private ArticleCacheService articleCacheService;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        List<ArticleEntity> articleList = articleCacheService.getLatestArticleList();
        env.setVariable("articleList", ObjectWrapper.DEFAULT_WRAPPER.wrap(articleList));
        body.render(env.getOut());
    }

    @Autowired
    public void setArticleCacheService(ArticleCacheService articleCacheService) {
        this.articleCacheService = articleCacheService;
    }
}
